<template>
    <a-row
        :gutter="8"
        :wrap="false">
        <a-col flex="auto">
            <x-search
                :collapsed="collapsed"
                :columns="{ sm: 1, md: 2, lg: 3, xl: 3, xxl: 4 }"
                :label-col="{ style: { width: '80px' } }"
                :model="searchFormData">
                <x-search-item
                    label="姓名"
                    name="name">
                    <a-input v-model:value="searchFormData.name"></a-input>
                </x-search-item>
                <x-search-item
                    label="手机号"
                    name="mobile">
                    <a-input v-model:value="searchFormData.mobile"></a-input>
                </x-search-item>
                <x-search-item
                    label="信用代码"
                    name="creditCode">
                    <a-input v-model:value="searchFormData.creditCode"></a-input>
                </x-search-item>
                <x-search-item
                    label="公司名称"
                    name="companyName">
                    <a-input v-model:value="searchFormData.companyName"></a-input>
                </x-search-item>
                <x-search-item
                    class="align-right"
                    suffix>
                    <a-space> </a-space>
                    <a-space>
                        <a-button @click="handleReset">重置</a-button>
                        <a-button
                            ghost
                            @click="search"
                            type="primary">
                            搜索
                        </a-button>
                        <a-modal
                            cancel-text="取消"
                            ok-text="确认"
                            :confirm-loading="modal.confirmLoading"
                            :open="modal.open"
                            :title="modal.title"
                            :width="480"
                            @cancel="closeModal"
                            @ok="closeModal">
                            <a-upload-dragger
                                v-model:fileList="fileList"
                                name="file"
                                :customRequest="upload">
                                <p class="ant-upload-drag-icon">
                                    <FileAddFilled />
                                </p>
                                <p class="ant-upload-text">上传催报名单文件</p>
                            </a-upload-dragger>
                            <a
                                @click="download"
                                size="small"
                                type="link"
                                >下载模板</a
                            >
                        </a-modal>
                        <a-button
                            type="primary"
                            @click="
                                () =>
                                    openModal({
                                        title: '上传文件',
                                    })
                            ">
                            上传催报名单
                        </a-button>

                        <a @click="() => (collapsed = !collapsed)">
                            展开
                            <template v-if="collapsed">
                                <down-outlined class="fs-12"></down-outlined>
                            </template>
                            <template v-else>
                                <up-outlined class="fs-12"></up-outlined>
                            </template>
                        </a>
                    </a-space>
                </x-search-item>
            </x-search>
            <a-card
                class="mt-8-2"
                type="flex"
                title="自动催报管理">
                <a-table
                    :columns="columns"
                    :data-source="listData"
                    :loading="loading"
                    :pagination="paginationState"
                    :scroll="{ x: 1000 }"
                    @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="'status' === column.key">
                            {{ record.status == 'ENABLED' ? '已启用' : '已禁用' }}
                        </template>
                        <template v-if="'action' === column.key">
                            <x-action-button @click="$refs.editDialogRef.handleEdit(record)">编辑</x-action-button>
                            <x-action-button
                                v-if="record.status == 'ENABLED'"
                                @click="del(record)"
                                >删除</x-action-button
                            >
                            <x-action-button
                                v-else
                                @click="send(record)"
                                >推送</x-action-button
                            >
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <edit-dialog
        ref="editDialogRef"
        :formItems="formItems"
        @ok="onOk"></edit-dialog>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { onMounted, ref } from 'vue'
import { DownOutlined, UpOutlined, FileAddFilled } from '@ant-design/icons-vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination, useModal } from '@/hooks'
import EditDialog from './components/EditDialog.vue'

defineOptions({
    name: 'systemRole',
})
const formItems = [
    { label: '催报人姓名', dataIndex: 'name', type: 'input' },
    { label: '催报人手机号', dataIndex: 'mobile', type: 'input' },
]
const columns = [
    { title: '姓名', dataIndex: 'name', fixed: 'left', width: 160 },
    { title: '催报人手机号', dataIndex: 'mobile' },
    { title: '公司名称', dataIndex: 'companyName' },
    { title: '社会统一信用代码', dataIndex: 'creditCode' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '操作', key: 'action', fixed: 'right', width: 120 },
]
const { modal, openModal, closeModal } = useModal()
const downloadUrl = `${config('http.apiBasic')}/statement/remind/sms/template/download`

const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } =
    usePagination()

const collapsed = ref(true)
const editDialogRef = ref()
const fileList = ref()
/**
 * 获取用户列表
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { code, data } = await apis.message
            .query({
                pageSize,
                pageNum: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === code) {
            const { records, pagination } = data
            listData.value = records
            paginationState.total = pagination.total
        }
    } catch (error) {
        hideLoading()
    }
}

const search = () => {
    getPageList()
}
function handleReset() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}
/**
 * 禁用用户
 */
function del({ id }) {
    Modal.confirm({
        title: '禁用提示',
        content: '确认禁用？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ;(async () => {
                    try {
                        const { code } = await apis.message.del(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === code) {
                            resolve()
                            message.success('禁用成功')
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
/**
 * 启用用户
 */
function send({ id }) {
    Modal.confirm({
        title: '启用提示',
        content: '确认启用？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ;(async () => {
                    try {
                        const { code } = await apis.message.send(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === code) {
                            resolve()
                            message.success('推送成功')
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
/**
 * 分页
 */
function onTableChange({ current, pageSize }) {
    paginationState.current = current
    paginationState.pageSize = pageSize
    getPageList()
}

/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}

const upload = async (current) => {
    const index = fileList.value.findIndex((item) => item.uid == current.file.uid)
    const onProgress = (load) => {
        fileList.value[index].percent = (load.loaded * 100) / load.total
    }
    const { code, data } = await apis.message
        .uploadPhoneNum({
            file: current.file,
        })
        .catch(() => {
            throw new Error()
        })
    if (config('http.code.success') === code) {
        fileList.value[index].status = 'done'
        fileList.value[index].error = ''
        message.success('上传成功')
    } else {
        fileList.value[index].status = 'error'
        fileList.value[index].error = ''
    }
}
function download() {
    const link = document.createElement('a')
    link.href = `${config('http.apiBasic')}/remind/sms/template/download`
    link.download = `催报名单模板`
    link.target = '_blank' // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click()
}
onMounted(() => {
    getPageList()
})
</script>

<style lang="less" scoped></style>
